package com.boot.core.entity;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description 建造者通用类
 * @date 2022/11/22 23:13
 **/

public class Builder<T> {

    private final Supplier<T> constructor;
    private final List<Consumer<T>> fieldInjects;

    private Builder(Supplier<T> constructor) {
        this.constructor = constructor;
        this.fieldInjects = new ArrayList<>();
    }

    public static <T> Builder<T> builder(Supplier<T> constructor) {
        return new Builder<>(constructor);
    }

    public <K> Builder<T> with(BiConsumer<T, K> consumer, K value) {
        Consumer<T> c = e -> consumer.accept(e, value);
        fieldInjects.add(c);
        return this;
    }

    public T build() {
        T e = constructor.get();
        fieldInjects.forEach(dInject -> dInject.accept(e));
        return e;
    }
}

